package com.anycl.springboot.springbootinaction.controller;

import com.anycl.springboot.springbootinaction.entity.User;
import com.anycl.springboot.springbootinaction.exception.FileNotUploadException;
import com.anycl.springboot.springbootinaction.exception.UserNotFoundException;
import com.fasterxml.jackson.annotation.JsonView;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {
    // http://localhost:8080/user/list?max=20&count=1
    @GetMapping("/list")
    public String users(Model model, @RequestParam Long max, @RequestParam(value = "num", defaultValue = "20") int count) {
        log.info("max: {}, count: {}", max, count);
        model.addAttribute("userList", Arrays.asList(new User(1L, "admin", "password"),
                new User(2L, "test", "password")));
        return "list";
    }

    /**
     * 转发url不变，重定向url会发生变化
     * 转发会携带HttpServletRequest里的信息，重定向不会携带
     * 最好的方式是debug
     * @param username
     * @return
     */
    @GetMapping("/{username}")
    public void userDetail(@PathVariable String username, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        log.info("username: {}", username);
//        return "redirect:/user/profile/" + username;
//        request.getRequestDispatcher("/user/profile/" + username).forward(request, response);
        response.sendRedirect("/user/profile/" + username);
        // return "forward:/user/profile/" + username;
    }

    @GetMapping("/profile/{username}")
    public String userProfile(@PathVariable String username, Model model, HttpServletRequest request, HttpServletResponse response) {
        // demo模拟用户没找到时的异常异常
        if (!new Random().nextBoolean()) {
            throw new UserNotFoundException();
        }
        model.addAttribute("username", username);
        return "profile";
    }

    /**
     * JsonView使用
     * @return
     */
    @GetMapping("/list/view")
    @ResponseBody
    @JsonView(User.UserView.class)
    public List<User> users() {
        return Arrays.asList(new User(1L, "admin", "password"),
                new User(2L, "test", "password"));
    }

    @GetMapping("/list/detail/view")
    @ResponseBody
    @JsonView(User.UserDetailView.class)
    public List<User> detailView() {
        return Arrays.asList(new User(1L, "admin", "password"),
                new User(2L, "test", "password"));
    }

    @GetMapping("/register")
    public String register() {
        return "register";
    }

    @PostMapping("/register")
    public String processRegistration(@Valid User user, /*@RequestParam("file") MultipartFile file, */Errors errors, Model model) throws IOException {
/*        log.info(file.toString());
        log.info(String.valueOf(file.getSize()));
        file.transferTo(new File("D:\\anyclPro\\files\\data\\" + file.getOriginalFilename()));*/
        log.info(user.toString());
        MultipartFile file = user.getFile();
        if (file == null || file.getSize() == 0) {
            log.info("文件为空");
            throw new FileNotUploadException("file not upload");
        }
        file.transferTo(new File("D:\\anyclPro\\files\\data\\" + file.getOriginalFilename()));
        if (errors.hasErrors()){
            model.addAttribute("errors", errors.getAllErrors());
            return "errors";
        }
       return "redirect:/user/profile/" + user.getUsername();
    }


    /**
     * 发送JSON数据到这个接口，Content-Type为application/json
     * @param user
     * @return
     */

    @PostMapping("/register/json")
    @ResponseBody
    @JsonView(User.UserView.class)
    public User processRegistrationWithJson(@RequestBody User user) {
        return user;
    }
}
